import axios from './axios.js'

import {
	getToken
} from '@/utils/auth'


export default function request(options) {
	const instance = axios.create({
		baseURL: options.AppURL || "",
		timeout: options.timeout || 10000,
		withCredentials: true,
		crossDomain: true,

	})

	// 请求拦截
	instance.interceptors.request.use(
		config => {
			let token = getToken();
			//设置请求头
			if (token) {
				config.headers['Authorization'] = 'Bearer ' + token;
			}

			//返回配置信息
			return config;
		},
		error => {
			return Promise.reject(error);
		}
	);

	// 响应拦截
	instance.interceptors.response.use(
		response => {
			//uni.setStorageSync('获取值的id值',任意类型存储值);
			if (response.status == 200) {
				return response.data;
			} else {
				return Promise.reject(response);
			}
		},
		error => {
			return Promise.reject(error);
		}
	);

	function settle(resolve, reject, response) {
		var validateStatus = response.config.validateStatus;
		if (!response.status || !validateStatus || validateStatus(response.status)) {
			resolve(response);
		} else {
			reject(response);
		}
	};

	//自定义适配器 ， 适配uniapp语法
	axios.defaults.adapter = function(config) {
		return new Promise((resolve, reject) => {
			let url = config.baseURL + axios.getUri(config);
			uni.request({
				method: config.method.toUpperCase(),
				url: config.baseURL + axios.getUri(config),
				header: config.headers,
				data: config.data,
				dataType: config.dataType,
				responseType: config.responseType,
				sslVerify: config.sslVerify,
				complete: function complete(response) {
					response = {
						data: response.data,
						status: response.statusCode,
						errMsg: response.errMsg,
						header: response.header,
						config: config
					};
					settle(resolve, reject, response);
				},
			});
		})
	}
	return instance;
}
